import { ElMessage } from 'element-plus';
import { defineStore } from 'pinia';
import {
  BaseFeatureSetReq,
  getChunkUploadedInfo,
  getImportedFiles,
} from 'src/api/featureSet';
import {
  UploadFeatureSetList,
  usePlatformFeatureSetUploadStore,
} from 'stores/platform-featureset-upload';
import { createFileChunk } from 'stores/platform-upload';
const platformUploadStore = usePlatformFeatureSetUploadStore();

export const usePlatformReUploadFeatureSetStore = defineStore(
  'platformReUploadFeatureSetStore',
  {
    state: () => ({
      reUploadModal: false,
      uploadedChunksRecord: {} as Record<string, Record<string, string[]>>,
      reUploadProcessId: [] as string[],
      reUploadList: [] as UploadFeatureSetList[],
    }),

    actions: {
      setReUploadList(lists: UploadFeatureSetList[]) {
        this.reUploadList = lists;
        platformUploadStore.setReUploadList(lists);
      },
      openModal() {
        this.reUploadModal = true;
      },
      closeModal() {
        this.reUploadModal = false;
      },
      mapperUploadId(
        feature_set_id: string,
        upload_id: string,
        row_name: string
      ) {
        platformUploadStore.platformUploadIdMapper[feature_set_id] =
          platformUploadStore.platformUploadIdMapper[feature_set_id] || {};
        platformUploadStore.platformUploadIdMapper[feature_set_id][row_name] =
          upload_id;
      },
      async prepareUploadChunks(uploadInfo: BaseFeatureSetReq) {
        const { feature_set_id } = uploadInfo;
        const fileRow =
          platformUploadStore.platformUploadFileList[feature_set_id];
        platformUploadStore.platformFeatureSetFileContainer[feature_set_id] =
          platformUploadStore.platformFeatureSetFileContainer[
            feature_set_id
          ] || {
            fileChunks: {},
            fileNoChunks: {},
          };
        if (!fileRow.length) return;
        let filename;
        for (const rowFile of fileRow) {
          filename = rowFile.name;
          const chunkUploadInfo = await getChunkUploadedInfo({
            ...uploadInfo,
            upload_id:
              platformUploadStore.platformUploadIdMapper[feature_set_id][
                filename
              ],
          });

          const uploadedChunksOrders = chunkUploadInfo.data.ids.map((id) =>
            String(Number(id) - 1)
          );
          this.uploadedChunksRecord[feature_set_id] =
            this.uploadedChunksRecord[feature_set_id] || {};

          this.uploadedChunksRecord[feature_set_id][filename] =
            uploadedChunksOrders;

          const filesResponse = await getImportedFiles({
            feature_set_id,
            project_id: uploadInfo.project_id,
          });
          const isContain = filesResponse.data.isImported;
          if (
            rowFile.raw &&
            rowFile.raw.size <= platformUploadStore.platformChunkSize
          ) {
            platformUploadStore.platformFeatureSetFileContainer[
              feature_set_id
            ].fileNoChunks[filename] = [
              {
                file: rowFile.raw,
                size: rowFile.raw.size,
                percentage: isContain
                  ? 100
                  : uploadedChunksOrders.length == 1
                  ? 100
                  : 0,
                filename: rowFile.name,
              },
            ];
          } else {
            const fileChunkList = createFileChunk(
              rowFile.raw!,
              platformUploadStore.platformChunkSize
            );
            platformUploadStore.platformFeatureSetFileContainer[
              feature_set_id
            ].fileChunks[filename] = fileChunkList.map(({ file }, index) => ({
              chunk: file,
              hash: rowFile.name + '-' + index,
              index: index,
              filename: rowFile.name,
              percentage: isContain
                ? 100
                : uploadedChunksOrders.includes(String(index))
                ? 100
                : 0,
              size: file.size,
              rowName: rowFile.name,
              rowSize: rowFile.size!,
            }));
          }
        }
      },

      async startContinueUpload(uploadInfo: BaseFeatureSetReq) {
        this.reUploadProcessId.push(String(uploadInfo.feature_set_id));
        platformUploadStore.setCurUploadFeatureSet(uploadInfo);
        platformUploadStore.clearVueUploadComponentFileList(
          uploadInfo.feature_set_id
        );
        await this.prepareUploadChunks(uploadInfo);
        await platformUploadStore.initPlatformUploadList();
        this.closeModal();
        platformUploadStore.openUploadModal();
        await this.continueUpload(uploadInfo, this.uploadedChunksRecord);
      },

      async continueUpload(
        featureSet: BaseFeatureSetReq,
        uploaded?: Record<string, Record<string, string[]>>
      ) {
        try {
          await platformUploadStore.prepareUploadUrls(featureSet);
          this.closeModal();
          platformUploadStore.openUploadModal();
        } catch (err) {
          ElMessage.error('请继续上传！');
        }
        await platformUploadStore.startUpload(featureSet, uploaded);
      },
    },
  }
);
